/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  OwnerLeaderCheckReportActivity.java   
 * @Package com.jiyi.activity.owner   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-10-11 下午1:56:58   
 * @version V1.0     
 */
package com.jiyi.activity.owner;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.adapter.DividerItemDecoration;
import com.jiyi.adapter.recyclerview.CommonAdapter;
import com.jiyi.adapter.recyclerview.base.ViewHolder;
import com.jiyi.adapter.recyclerview.wrapper.EmptyWrapper;
import com.jiyi.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;
import com.jiyi.bean.owner.CheckReportBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.inteface.WebApi;
import com.jiyi.activity.WebActivity;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.DialogTool;
import com.swift.utils.MonPickerDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @ClassName: OwnerLeaderCheckReportActivity
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: HYM
 * @date: 2017-10-11 下午1:56:58
 * 
 */
public class OwnerCheckReportActivity extends ActivityBase {

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	@BindView(R.id.tvSearchDate)
	TextView tvSearchDate;
	@BindView(R.id.mainList)
	RecyclerView mainList;

	EmptyWrapper adapter;
	LayoutInflater inflater;
	private List<CheckReportBean> dataList = new ArrayList<CheckReportBean>();
	private int mYear;
	private int mMonth;
	private int mDay;
	
	Dialog dialog;
	String compaynId="";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_owner_leader_checkreport);
		ButterKnife.bind(this);
		init();
	}

	private void init() {
		inflater = LayoutInflater.from(this);
		getIntentData();
		setTop();
		initViewState();
		setAdapter();
		getData(null);
	}

	private void getIntentData() {
		compaynId = getIntent().getStringExtra("companyId");	
	}

	private void setTop() {
		tvTitle.setText("检测报告");
		tvSearch.setVisibility(View.GONE);
	}

	private void getData(String task_time) {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		if (UserInfoUtil.getCurrentUserRole() == AppConfig.PROJECT_MNG) {
			params.put("company_id", UserInfoUtil.getCurrentUserDepartId()+"");
		}
		else {
			params.put("company_id", compaynId);
		}
		
		if (!TextUtils.isEmpty(task_time)) {
			params.put("task_time", task_time);
		}

		VolleyRequest.StringRequestPost(this,
				WebApi.MAINTENANCE_OWNER_CHECKREPORT_LIST, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<CheckReportBean> temp = new Gson()
										.fromJson(
												data,
												new TypeToken<List<CheckReportBean>>() {
												}.getType());
								dataList.clear();
								dataList.addAll(temp);
								adapter.notifyDataSetChanged();
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	private void setAdapter() {

		// 设置布局管理器
		mainList.setLayoutManager(new LinearLayoutManager(this));
		mainList.addItemDecoration(new DividerItemDecoration(this,
				DividerItemDecoration.VERTICAL_LIST, null));
		// 初始化适配器
		CommonAdapter mCommonAdapter = new CommonAdapter<CheckReportBean>(this,
				R.layout.item_check_report_list, dataList) {
			@Override
			protected void convert(final ViewHolder holder,
					final CheckReportBean t, final int position) {
				holder.setText(R.id.tvDate, t.getTask_time());
				holder.setOnClickListener(R.id.tvDownload,
						new OnClickListener() {

							@Override
							public void onClick(View v) {
								getFileUrl(t.getTask_id());
							}
						});
				holder.setOnClickListener(R.id.tvDetail, new OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(v.getContext(),WebActivity.class);
						intent.putExtra("title", "检测报告");
						intent.putExtra("isHideTitle", false);
						intent.putExtra("url", WebApi.CHECKREPORT_DETAIL+"/access_token/"+UserInfoUtil.getCurrentUserAccessToken()+"/id/"+t.getTask_id());
						v.getContext().startActivity(intent);
					}
				});
			}
		};

		HeaderAndFooterWrapper mHeaderAndFooterWrapper = new HeaderAndFooterWrapper(
				mCommonAdapter);
		View headView = inflater.inflate(R.layout.item_check_report_list_head,
				mainList, false);
		headView.setTag("head");
		mHeaderAndFooterWrapper.addHeaderView(headView);

		adapter = new EmptyWrapper(mHeaderAndFooterWrapper);
		adapter.setEmptyView(R.layout.empty_view);

		mainList.setAdapter(adapter);
		adapter.notifyDataSetChanged();
	}

	private void initViewState() {
		tvSearchDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				onCreateDialog().show();
			}
		});
	}

	void search() {
		getData(tvSearchDate.getText().toString());
	}

	void downLoad(String url, final String fileName) {
		OkHttpUtils
				.get()
				.url(url)
				.build()
				.execute(
						new FileCallBack(Environment
								.getExternalStorageDirectory()
								.getAbsolutePath()
								+ "/CheckReport", fileName) {

							@Override
							public void onError(Call arg0, Exception e, int arg2) {
								Log.e(" sdfdsfdsf ",
										"onError :" + e.getMessage());
							}

							@Override
							public void onResponse(File file, int arg1) {
								Log.e(" sdfdsfdsf ",
										"onResponse :" + file.getAbsolutePath());
								ToastUtil.getInstances().showMsg(
										"已下载到sdcard下的" + fileName);

							}
						});
	}
	
	void getFileUrl(String task_id) {
		dialog = DialogTool.showDialog(dialog, this);
		OkHttpUtils
				.get()
				.addParams(AppConfig.ACCESS_TOKEN,
						UserInfoUtil.getCurrentUserAccessToken())
				.addParams("task_id", task_id)
				.url(WebApi.MAINTENANCE_OWNER_CHECKREPORT_DOWNLOAD).build()
				.execute(new StringCallback() {

					@Override
					public void onResponse(String result, int arg1) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								JSONObject dataObj = new JSONObject(data);
								String fileName = dataObj.getString("fileName");
								String fileAddr = dataObj.getString("fileAddr");
								downLoad(fileAddr, fileName);
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							DialogTool.hideDialog(dialog);
						}
					}

					@Override
					public void onError(Call arg0, Exception arg1, int arg2) {
						DialogTool.hideDialog(dialog);
						ToastUtil.getInstances().showMsg("下载文件出错~");
					}
				});
	}

	protected Dialog onCreateDialog() {
		Calendar dateAndTime = Calendar.getInstance(Locale.CHINA);
		mYear = dateAndTime.get(Calendar.YEAR);
		mMonth = dateAndTime.get(Calendar.MONTH);
		mDay = dateAndTime.get(Calendar.DAY_OF_MONTH);
		return new MonPickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			String mm;
			String dd;
			if (monthOfYear < 9) {
				mMonth = monthOfYear + 1;
				mm = "0" + mMonth;
			} else {
				mMonth = monthOfYear + 1;
				mm = String.valueOf(mMonth);
			}
			if (dayOfMonth <= 9) {
				mDay = dayOfMonth;
				dd = "0" + mDay;
			} else {
				mDay = dayOfMonth;
				dd = String.valueOf(mDay);
			}
			mDay = dayOfMonth;
			tvSearchDate.setText(String.valueOf(mYear) + "-" + mm);
			search();
		}
	};
	
	@OnClick({ R.id.tvBack })
	public void onClick(View view) {
		Intent intent = null;
		switch (view.getId()) {
		case R.id.tvBack:
			finish();
			break;
		default:
			break;
		}
	}
}
